import hashlib
import json
import os

# 用户存储结构
user_list = []
PASSWD_FILE = "passwd"

def hash_password(password):
    """对密码进行SHA256哈希加密"""
    sha256 = hashlib.sha256()
    sha256.update(password.encode('utf-8'))
    return sha256.hexdigest()


def load():
    """从 passwd 文件加载用户数据"""
    global user_list
    if os.path.exists(PASSWD_FILE):
        try:
            with open(PASSWD_FILE, 'r', encoding='utf-8') as f:
                content = f.read()
                if content:
                    user_list = json.loads(content)
                else:
                    user_list = [] # 文件为空
        except (json.JSONDecodeError, IOError) as e:
            print(f"Error loading user data: {e}")
            user_list = [] # 加载失败则重置
    else:
        user_list = [] # 文件不存在

def save():
    """将用户数据保存到 passwd 文件"""
    try:
        with open(PASSWD_FILE, 'w', encoding='utf-8') as f:
            json.dump(user_list, f, ensure_ascii=False, indent=4)
    except IOError as e:
        print(f"Error saving user data: {e}")





def login(id, password):
    """
    登录函数
    :param id: 用户ID
    :param password: 用户密码
    :return: (True, "登录成功") 或 (False, "用户不存在") 或 (False, "密码错误")
    """
    load()
    pwd_hash = hash_password(password)
    for user in user_list:
        if user['id'] == id:
            if user['pwd_hash'] == pwd_hash:
                return True, "登录成功"
            else:
                return False, "密码错误"
    return False, "用户不存在"

def register(id, password):
    """
    注册函数
    :param id: 用户ID
    :param password: 用户密码
    :return: (True, "注册成功") 或 (False, "用户名已存在")
    
    """
    load()
    for user in user_list:
        if user['id'] == id:
            return False, "用户名已存在" # 返回 False 和消息
    pwd_hash = hash_password(password)
    user_list.append({"id": id, "pwd_hash": pwd_hash})
    save() # 保存更新后的用户列表
    return True, "注册成功" # 返回 True 和消息

# 测试代码
if __name__ == "__main__":
    # 注册用户
    print(register("abc", "123456"))  # (True, "注册成功")
    print(register("def", "password"))  # (True, "注册成功")
    print(register("abc", "newpassword"))  # (False, "用户名已存在")
    

    # 登录用户
    print(login("abc", "123456"))  # (True, "登录成功")
    print(login("abc", "wrongpassword"))  # (False, "密码错误")
    print(login("unknown", "password"))  # (False, "用户不存在")
